﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using XREditor.Dtos;
using XREditor.Models;

namespace XREditor.Controllers
{
    /// <summary>
    /// 类型管理
    /// </summary>
    [DynamicApiController]
    public class CategoryController
    {
        private readonly ILogger<CategoryController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public CategoryController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 类型列表
        /// </summary>
        /// <param name="ulsfd">参照下方Schemas中：CategorySearchListFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] CategorySearchListFormDto cslfd)
        {
            List<Category> categorys = await db.Queryable<Category>()
                .Where(cg => cg.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(cslfd.Content), cg => cg.Name.Contains(cslfd.Content))
                .ToListAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = categorys.Adapt<List<CategoryInfoFormDto>>(),
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加类型
        /// </summary>
        /// <param name="uifd">参照下方Schemas中：CategoryInfoFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] CategoryInfoFormDto cifd)
        {
            // 如果名称重复提示不让添加
            bool isExist = await db.Queryable<Category>().Where(cg => cg.Name == cifd.Name).AnyAsync();
            if (isExist) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = cifd,
                    Errors = "类型名称已存在",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            await db.Insertable<Category>(cifd.Adapt<Category>()).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = cifd,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除类型
        /// </summary>
        /// <param name="pfd">参照下方Schemas中：PrimaryFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] PrimaryFormDto pfd) {
            await db.Updateable<Category>().SetColumns(t => t.IsActive == 0).Where(t => t.Id == pfd.Id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改类型
        /// </summary>
        /// <param name="uifd">参照下方Schemas中：CategoryInfoFormDto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] CategoryInfoFormDto mxifd) {
            // 拿到修改前的类型名称
            Category category = await db.Queryable<Category>()
                .InSingleAsync(mxifd.Id);

            // 更新category表name字段
            await db.Updateable<Category>(mxifd.Adapt<Category>()).ExecuteCommandAsync();

            // 更新moxing表所有type字段
            await db.Updateable<MoXing>()
                .SetColumns(mx => mx.Type == mxifd.Name)
                .Where(mx => mx.Type == category.Name)
                .ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = mxifd,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看类型
        /// </summary>
        /// <param name="pfd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] PrimaryFormDto pfd) {
            Category category = await db.Queryable<Category>()
                .InSingleAsync(pfd.Id);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = category.Adapt<CategoryInfoFormDto>(),
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

    }
}
